﻿using System;

namespace Gonte.Validation
{
    /// <summary>
    /// Validates the range for string fields only
    /// </summary>
    public class FieldLengthValidator
        : FieldValidator
    {
        private const string StringOutOfRangeError = "Length of string: {0} is out of range [{1}, {2}]";

        public FieldLengthValidator(int minLength, int maxLength)
            : base(typeof(string))
        {
            this.Type = typeof(string);
            minLength_ = minLength;
            maxLength_ = maxLength;
        }

        public override bool Validate(Object value)
        {
            if (!base.Validate(value))
            {
                return false;
            }

            if (value == null)
            {
                return true; // We don't validate nulls here
            }

            int length = value.ToString().Length;

            if (!Range<int>.IsInRange(length, minLength_, maxLength_))
            {
                error_ = string.Format(StringOutOfRangeError, length, minLength_, maxLength_);
                return false;
            }

            return true;
        }

        private int minLength_;
        private int maxLength_;
    }
}
